// components/AddRoleDialog.tsx
import React, { useState } from 'react';
import {
  Dialog, DialogTitle, DialogContent, TextField, Checkbox,
  Typography, Box, Button, Stack
} from '@mui/material';

type AddRoleDialogProps = {
  open: boolean;
  allPermissions: string[];
  onSubmit: (roleName: string, permissions: string[]) => void;
  onClose: () => void;
};

const AddRoleDialog: React.FC<AddRoleDialogProps> = ({ open, allPermissions, onSubmit, onClose }) => {
  const [roleName, setRoleName] = useState('');
  const [selectedPermissions, setSelectedPermissions] = useState<string[]>([]);

  const handleToggle = (perm: string) => {
    setSelectedPermissions(prev =>
      prev.includes(perm)
        ? prev.filter(p => p !== perm)
        : [...prev, perm]
    );
  };

  const handleSubmit = () => {
    if (!roleName.trim()) return;
    onSubmit(roleName.trim(), selectedPermissions);
    setRoleName('');
    setSelectedPermissions([]);
  };

  const handleClose = () => {
    setRoleName('');
    setSelectedPermissions([]);
    onClose();
  };

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      maxWidth="sm"
      fullWidth
      PaperProps={{
        sx: {
          backgroundColor: '#102840',
          borderRadius: 2,
          p: 2
        }
      }}
    >
      <DialogTitle sx={{ color: '#90CAF9' }}>新增角色</DialogTitle>
      <DialogContent>
        <Box mt={1}>
          <TextField
            label="角色名称"
            fullWidth
            variant="outlined"
            value={roleName}
            onChange={e => setRoleName(e.target.value)}
            sx={{ mb: 2 }}
            InputLabelProps={{ style: { color: '#90CAF9' } }}
            inputProps={{ style: { color: '#fff' } }}
          />

          <Typography sx={{ color: '#90CAF9', mb: 1 }}>选择权限</Typography>
          <Box display="flex" flexDirection="column" gap={1}>
            {allPermissions.map(perm => (
              <Box key={perm} display="flex" alignItems="center">
                <Checkbox
                  checked={selectedPermissions.includes(perm)}
                  onChange={() => handleToggle(perm)}
                  sx={{ color: '#90CAF9' }}
                />
                <Typography sx={{ color: '#fff' }}>{perm}</Typography>
              </Box>
            ))}
          </Box>

          <Stack direction="row" spacing={2} sx={{ mt: 3 }}>
            <Button variant="contained" onClick={handleClose}>取消</Button>
            <Button
              variant="contained"
              sx={{ backgroundColor: '#2E7D32' }}
              onClick={handleSubmit}
            >
              提交
            </Button>
          </Stack>
        </Box>
      </DialogContent>
    </Dialog>
  );
};

export default AddRoleDialog;
